<?php


namespace coco;


class Response
{
    protected $data;
    protected $raw = '';
    protected $type;
    protected $header = [];

    public static function view($data)
    {
        $obj = new self([
            'type' => 'view',
        ]);
        $obj->setData($data);
        return $obj;
    }

    const content_type = [
        'json' => 'content-type:application/json;charset=utf-8',
        'view' => 'content-type:text/html;charset=utf-8',
        'html' => 'content-type:text/html;charset=utf-8',
        'txt' => 'content-type:text/plain;charset=utf-8',
        'text' => 'content-type:text/plain;charset=utf-8',
        'gif' => 'content-type:image/gif',
        'png' => 'content-type:image/png',
        'jpg' => 'content-type:image/jpeg',
        'jpeg' => 'content-type:image/jpeg',
        'xml' => 'content-type:application/xml;charset=utf-8',
        'pdf' => 'content-type:application/pdf;charset=utf-8',
    ];

    public function __construct(array $option = [])
    {
        $this->type = $option['type'] ?? 'json';
    }

    public function setData(array $data)
    {
        $this->data = $data;
    }

    public function setHeader(string $header)
    {
        $this->header[] = $header;
    }

    protected function sendHeader()
    {
        if (!headers_sent()) {
            array_map(function ($header) {
                header($header);
            }, $this->header);
        }
    }

    protected function parse()
    {
        switch ($this->type) {
            case 'json':
                $this->raw = json_encode($this->data, JSON_UNESCAPED_UNICODE);
                break;
            case 'view':
                ob_start();
                $real_controller = Request::getInstance()->getRealController();
                $real_controller_array = explode('\\', $real_controller);
                $real_controller = join(DIRECTORY_SEPARATOR, array_map(function ($v) {
                    return class2url($v);
                }, $real_controller_array));
                $path = Tree::getInstance()->get('app')->app_path . str_replace(DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'controller', 'view',
                        $real_controller .
                        DIRECTORY_SEPARATOR . Request::getInstance()->getRealMethod()) . '.php';
                extract($this->data);
                include $path;
                $this->raw = ob_get_contents();
                ob_end_clean();
                break;
            default:
                $this->raw = $this->data[$this->type] ?? '';
        }
        $this->header[] = self::content_type[strtolower($this->type)] ?? 'content-type:application/octet-stream';
        $this->header[] = 'Content-Length: ' . strlen($this->raw);
    }

    public function send()
    {
        $this->parse();
        $this->sendHeader();
        file_put_contents('php://output', $this->raw);
    }
}